package com.jmp.security.client;

import com.jmp.base.dto.AccountCompanyKeyRequest;
import com.jmp.base.dto.AccountResponse;
import com.jmp.feign.AccountFeign;
import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.ClientDetailService;
import com.jmp.security.base.RequestDetail;
import one.stand.enums.CompanyStateEnums;
import one.stand.mapper.CompanyMapperExt;
import one.stand.model.Company;
import one.stand.model.ResultModel;
import one.stand.service.CompanyEquService;
import one.stand.util.AssertUtil;
import org.springframework.util.Assert;

public class EqucodeClientDetailService implements ClientDetailService {
    private CompanyMapperExt companyMapperExt;
    private AccountFeign accountFeign;
    private CompanyEquService companyEquService;

    public EqucodeClientDetailService(CompanyMapperExt companyMapperExt, AccountFeign accountFeign, CompanyEquService companyEquService) {
        this.companyMapperExt = companyMapperExt;
        this.accountFeign = accountFeign;
        this.companyEquService = companyEquService;
    }

    @Override
    public ClientDetail get(RequestDetail requestDetail) {
        Assert.notNull(requestDetail.getEquCode(), "设备号不能为空");
        Integer companyId = companyEquService.check(requestDetail.getEquCode(), CompanyEquService.TYPE_IPAD).getCompanyId();
        Assert.notNull(companyId, "当前设备未授权，请联系软件提供商授权！\n您的设备编号：" + requestDetail.getEquCode() + "\n联系电话：0579-86669669");

        Company companyModel = companyMapperExt.selectByPrimaryKey(companyId);
        Assert.notNull(companyModel, "企业不存在");
        Assert.isTrue(CompanyStateEnums.NORMAL.getState().equals(companyModel.getCompanyState()), "企业已禁用，请联系客服");

        String companyKey = companyModel.getCompanyKey();
        AccountCompanyKeyRequest accountCompanyKeyRequest = AccountCompanyKeyRequest.builder()
                .companyKey(companyKey)
                .loginEnum(requestDetail.getLoginEnum())
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyKeyDefaultIfNull(accountCompanyKeyRequest);
        AssertUtil.isTrue(accountResponseResultModel);
        AssertUtil.nonNull(accountResponseResultModel.getData(), "未购买服务，请联系客服");
        AssertUtil.isTrue(requestDetail.getCompanyKey().equals(accountResponseResultModel.getData().getCompanyKey()), "未加入本平台，请联系客服");

        return ClientDetail.builder()
                .companyId(companyId)
                .companyKey(companyKey)
                .equCode(requestDetail.getEquCode())
                .companyAccountModel(accountResponseResultModel.getData())
                .build();
    }
}
